﻿using Gp.Input;
using UnityEngine;
using UnityEngine.UI;

namespace GP.Scripts.GUI {

    public class MaskAnimation : MonoBehaviour
    {
        public float animationSpeed = 1.0f;
        private Image maskImage;
        private int number = 0;
        private bool _executeing = false;
        void Start()
        {
            // 获取Mask的RectTransform
            maskImage = GetComponent<Image>();
            maskImage.enabled = false;
        }

        void Update()
        {
            // 控制遮罩的展开效果
            if (Global.Get<InputManager>().IsRunning()) {
                maskImage.enabled = true;
                _executeing = true;
            }

            if (_executeing) {
                ExpandMask();
            }
        }

        void ExpandMask()
        {
            // 计算遮罩的角度（随时间展开）
            float currentAngle = number * animationSpeed * 360f;
        
            // 创建一个顺时针旋转的矩形
            Texture2D texture = new Texture2D(64, 64);
            for (int y = 0; y < texture.height; y++)
            {
                for (int x = 0; x < texture.width; x++)
                {
                    float angle = Mathf.Atan2(y - texture.height / 2, x - texture.width / 2) * Mathf.Rad2Deg;
                    angle = (angle + 360) % 360; // 转换为正值

                    if (angle < currentAngle)
                    {
                        texture.SetPixel(x, y, Color.clear);
                    }
                    else
                    {
                        texture.SetPixel(x, y, Color.black);
                    }
                }
            }

            texture.Apply();

            // 应用遮罩纹理
            maskImage.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));

            if (number == 360) {
                number = 0;
                _executeing = false;
                return;
            };

            number += 1;
        }
    }
}